#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "winusbdriver.h"

WinUSBDriver winusb;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    this->setWindowTitle("WINUSB测试");
    
    connect(&winusb,SIGNAL(recvSignals(unsigned char *,int)),this,SLOT(usbRecvSlot(unsigned char *,int)));
    connect(&winusb,SIGNAL(disconnectSignals()),this,SLOT(disconnectSlot()));
    
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::usbRecvSlot(unsigned char *buf,int len)
{
    if(ui->chkBoxHexRecv->isChecked())
    {
        QString fmtString;
        for(int i = 0; i < len; i++)
        {
            fmtString += QString::asprintf("%02X ", buf[i] & 0XFF);
        }
        ui->te_recv->append(fmtString);
    }else
    {
        QTextCodec* codec = QTextCodec::codecForName("GBK");
        QString text = codec->toUnicode(QByteArray((char *)buf, len));
        ui->te_recv->append(text);
    }
}

void MainWindow::on_pb_open_clicked()
{
    if(ui->pb_open->text().compare(QString::fromUtf8("打开")) == 0)
    {
        int vid = ui->le_vid->text().toInt();
        int pid = ui->le_pid->text().toInt();
        if(winusb.open(vid,pid) == 0)
        {
            ui->pb_open->setText("关闭");
        }
    }else
    {
        winusb.close();
        ui->pb_open->setText("打开");
    }   
}
void MainWindow::disconnectSlot(void)
{
    winusb.close();
    ui->pb_open->setText("打开");
}

void MainWindow::on_pb_send_clicked()
{
    QString text = ui->te_send->toPlainText();
    if(ui->chkBoxHexSend->isChecked())
    {
        text.remove(" ");
        QByteArray data(text.length() / 2, 0);
        uint32_t size = 0;
        StrToHex(text.toStdString().c_str(), text.length(), (uint8_t *)data.data(), &size);
        winusb.send(data);
    }else
    {
        QTextCodec* codec = QTextCodec::codecForName("GBK");
        QByteArray data = codec->fromUnicode(text);
        winusb.send(data);
    }
}

void MainWindow::on_chkBoxHexSend_toggled(bool checked)
{
    QString fmtString;
    QString text = ui->te_send->toPlainText();
    if(checked)
    {
        QTextCodec* codec = QTextCodec::codecForName("GBK");
        QByteArray data = codec->fromUnicode(text);
        for(int i = 0; i < data.size(); i++)
            fmtString += QString::asprintf("%02X ", data[i] & 0XFF);
    }else
    {
        text.remove(" ");
        QByteArray data(text.length() / 2, 0);
        uint32_t size = 0;
        StrToHex(text.toStdString().c_str(), text.length(), (uint8_t *)data.data(), &size);
        QTextCodec* codec = QTextCodec::codecForName("GBK");
        fmtString = codec->toUnicode(data);
    }
    ui->te_send->setText(fmtString);
}
